package lumis.doui.control.conditional;

import javax.servlet.jsp.el.ELException;

import org.w3c.dom.Node;

import lumis.doui.control.Control;
import lumis.doui.control.ControlException;
import lumis.portal.PortalException;
import lumis.portal.el.LumisExpressionEvaluatorImpl;
import lumis.util.XmlUtil;

/**
 * Used to specify a condition under which the control and its children must be rendered. 
 * <br/>
 * <br/>
 * Example use:
 * <xmp>
 * <control:lum_conditionalRender>
 * 		<condition>source.sourceContainer.sourcesMap.blog.data.owner.id == douiContext.request.sessionConfig.userId</condition>
 * </control:lum_conditionalRender>
 * </xmp>
 * 
 * @version $Revision: 11470 $ $Date: 2010-04-29 12:39:58 -0300 (Thu, 29 Apr 2010) $
 * @since 4.2.0
 */
public class ConditionalRenderControl extends Control
{
	private final LumisExpressionEvaluatorImpl evaluator = new LumisExpressionEvaluatorImpl();

	@Override
	public void setRenderData() throws PortalException
	{
		Node conditionNode = XmlUtil.selectSingleNode("condition", controlDefinitionNode);
		
		if(conditionNode == null)
			throw new ControlException("Precondition node not specified.");
		
		String conditionExpression = conditionNode.getTextContent();
		try
		{
			if(((Boolean)evaluator.evaluate("${"+conditionExpression+"}", Boolean.class, this, null)).booleanValue())
			{
				super.setRenderData();
			}
			else
			{
				controlDefinitionNode.getParentNode().removeChild(controlDefinitionNode);
			}
		}
		catch (ELException e)
		{
			// ignore this EL exception. This expression may be processed at a later stage.
		}
	}

}
